package com.example.administrator.mywebviewdemo;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.just.library.AgentWeb;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;

public class MainActivity extends AppCompatActivity {
    public final static String PARAM_URL = "param_url";

    public final static String PARAM_MODE = "param_mode";

    private SonicSession sonicSession;


    private AgentWeb mAgentWeb;
    private RelativeLayout mRelativeLayout;
    private WebSettings webSettings;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        Intent intent = getIntent();
        String url = "https://www.baidu.com";
        int mode = 2;
        if (TextUtils.isEmpty(url) || -1 == mode) {
            finish();
            return;
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl sonicSessionClient = null;

        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(url,  new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            throw new UnknownError("create session fail!");
        }

        // step 3: BindWebView for sessionClient and bindClient for SonicSession
        // in the real world, the init flow may cost a long time as startup
        // runtime、init configs....
        setContentView(R.layout.activity_main);
//        WebView webView = (WebView) findViewById(R.id.webview);
        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(mRelativeLayout,new RelativeLayout.LayoutParams(-1,-1) )//
                .useDefaultIndicator()//
                .setIndicatorColor(ContextCompat.getColor(MainActivity.this,R.color.colorAccent))
//                .setReceivedTitleCallback(mCallback)
                .setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onReceivedTitle(WebView view, String title) {
                        super.onReceivedTitle(view, title);
                        // android 6.0 以下通过title获取
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                            if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                                view.loadUrl("about:blank");// 避免出现默认的错误界面
                            }
                        }
                    }



                    @Override
                    public void onProgressChanged(WebView view, int newProgress) {
                        //加载完成
                        if (newProgress == 100) {
                            Log.e("TAG","newProgress == 100");
                        }
                    }
                })
                .setWebViewClient(new WebViewClient() {
                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        if (sonicSession != null) {
                            sonicSession.getSessionClient().pageFinish(url);
                        }
                    }

                    @TargetApi(21)
                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                        return shouldInterceptRequest(view, request.getUrl().toString());
                    }

                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                        if (sonicSession != null) {
                            //step 6: Call sessionClient.requestResource when host allow the application
                            // to return the local data .
                            return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                        }
                        return null;
                    }
                })
                .setSecutityType(AgentWeb.SecurityType.strict)
                .createAgentWeb()//
                .ready()
                .go(url);
        webSettings =  mAgentWeb.getAgentWebSettings().getWebSettings();
        webSettings.setUseWideViewPort(false);
        webSettings.setMinimumFontSize(6);
        WebView webView = mAgentWeb.getWebCreator().get();
        // step 4: bind javascript
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "nativeMethod");

        // step 5: webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(url);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void initView() {
        mRelativeLayout = (RelativeLayout) findViewById(R.id.ll);
    }
    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }
}
